import React, { Component, useRef } from 'react'
import { SearchOutlined } from "@ant-design/icons";
import { Form, Input, Space, Button } from "antd";
import _ from 'lodash';
import TheButton from '@/components/TheButton';
import TheTable from '@/components/TheTable';
import ThePagination from '@/components/ThePagination';
import TheDialog from '@/components/TheDialog';
import { apiGetChauffeurPage, apiGetChauffeurAdd, apiGetChauffeurEdit, apiGetChauffeurDel, apiGetMemberTripPage } from '@/request/petTaxi';

const SearchHeader = ({ openDialog, getValue }) => {
  const formRef = useRef()
  const onFinish = (values) => {
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      storeChauffeurId: '',
      chauffeurName: ''
    })
    getValue({})
  }
  return (
    <div
      className="p-search-box"
      style={{ display: "flex", justifyContent: "space-between" }}
    >
      <Form ref={formRef} onFinish={onFinish} layout="inline">
        <Form.Item name="storeChauffeurId">
          <Input suffix={<SearchOutlined />} placeholder={"请输入司机ID"} />
        </Form.Item>
        <Form.Item name="chauffeurName">
          <Input suffix={<SearchOutlined />} placeholder={"请输入司机姓名"} />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button htmlType="submit" type="primary">搜索</Button>
            <Button onClick={reset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
      <TheButton type="default" size="middle" onClick={openDialog}>
        新增司机
      </TheButton>
    </div>
  );
};


export default class Driver extends Component {
  state = {
    columns: [
      {
        title: '司机ID',
        dataIndex: 'storeChauffeurId',
        key: 'storeChauffeurId'
      },
      {
        title: '司机姓名',
        dataIndex: 'chauffeurName',
        key: 'chauffeurName'
      },
      {
        title: '联系电话',
        dataIndex: 'chauffeurMobile',
        key: 'chauffeurMobile'
      },
      {
        title: '操作',
        render: (text, record) => {
          return <>
            <TheButton haspermi={['taxi:driver:nowTrip']} onClick={() => this.openNowDialog(record)}>当前行程</TheButton>
            <TheButton haspermi={['taxi:driver:historyTrip']} onClick={() => this.props.history.push(`/taxi/driver/history/${record.storeChauffeurId}`)}>历史行程</TheButton>
            <TheButton haspermi={['taxi:driver:edit']} onClick={() => this.editDialog(record)}>编辑</TheButton>
            <TheButton haspermi={['taxi:driver:delete']} onClick={() => this.delConfirm(record.storeChauffeurId)}>删除</TheButton>
          </>
        }
      },
    ],
    dataSource: [1],
    pageData: {
      pageNo: 1,
      pageSize: 10
    },
    total: 0,
    loading: false,
    searchValue: {},
    title: '新增司机',
    visible: false,
    nowVisible: false,
    nowColumns: [
      {
        title: '乘客姓名',
        dataIndex: 'contactName',
        key: 'contactName'
      },
      {
        title: '联系方式',
        dataIndex: 'contactPhone',
        key: 'contactPhone'
      },
      {
        title: '起点',
        dataIndex: 'originAddressDetail',
        key: 'originAddressDetail'
      },
      {
        title: '终点',
        dataIndex: 'destinationAddressDetail',
        key: 'destinationAddressDetail'
      },
      {
        title: '里程',
        dataIndex: 'totalMileage',
        key: 'totalMileage',
        render: (text, record) => {
          return React.$transNum(text, 2, -3) + '公里'
        }
      },
      {
        title: '支付金额',
        dataIndex: 'totalPrice',
        key: 'totalPrice',
        render: (text, record) => {
          return <React.$Price price={text || 0} />
        }
      },
      {
        title: '车牌号',
        dataIndex: 'vehicleBrand',
        key: 'vehicleBrand'
      },
      {
        title: '订单时间',
        dataIndex: 'createTime',
        key: 'createTime'
      },
      {
        title: '行程状态',
        dataIndex: 'tripStatus',
        key: 'tripStatus',
        render: (text, record) => {
          let label = '';
          switch (text) {
            case '0':
              label = '乘客取消订单';
              break;
            case '1':
              label = '待支付';
              break;
            case '2':
              label = '等待司机确认';
              break;
            case '3':
              label = '司机已接单 正在赶往乘车地点';
              break;
            case '4':
              label = '司机已到达 等待乘客';
              break;
            case '5':
              label = '乘客已到达 确认上车';
              break;
            case '9':
              label = '行程结束';
              break;
          }
          return label;
        }
      },
    ],
    nowData: [1],
    nowLoading: false,
    storeChauffeurId: '',
    editValue: {},
    btnLoading: false
  }
  componentDidMount() {
    this.getData()
  }
  getData = async () => {
    this.setState({ loading: true })
    const { pageData, searchValue } = this.state
    let res = await apiGetChauffeurPage({ ...pageData, ...searchValue })
    if (res.data && res.code === 0) {
      this.setState({
        dataSource: res.data,
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        total: res.totalCount
      })
    }
    this.setState({ loading: false })
  }
  getValue = value => {
    this.setState({
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      searchValue: value
    }, () => this.getData())
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => this.getData())
  }
  openDialog = () => {
    this.setState({
      visible: true,
      title: '新增司机'
    })
  }
  editDialog = (value) => {
    this.setState({
      editValue: value,
      storeChauffeurId: value.storeChauffeurId,
      visible: true,
      title: '编辑司机'
    })
  }
  closeDialog = () => {
    this.setState({
      editValue: {},
      storeChauffeurId: '',
      visible: false,
      title: '新增司机'
    })
  }
  saveDriver = async value => {
    const { storeChauffeurId } = this.state
    this.setState({ btnLoading: true })
    if (!storeChauffeurId) {
      let res = await apiGetChauffeurAdd({ ...value })
      if (res.code === 0) {
        React.$message({
          type: 'info',
          content: '新增成功'
        })
        this.closeDialog()
        this.getData()
      }
    } else {
      let res = await apiGetChauffeurEdit({ storeChauffeurId, ...value })
      if (res.code === 0) {
        React.$message({
          type: 'info',
          content: '修改成功'
        })
        this.closeDialog()
        this.getData()
      }
    }
    this.setState({ btnLoading: false })
  }
  delConfirm = (storeChauffeurId) => {
    React.$confirm({
      title: '您确认删除此司机信息吗？',
      onOk: async () => {
        let res = await apiGetChauffeurDel({ storeChauffeurId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '删除成功'
          })
          this.getData()
        }
      }
    })
  }
  openNowDialog = async (value) => {
    this.setState({ nowLoading: true })
    const { storeChauffeurId } = value
    let res = await apiGetMemberTripPage({
      storeChauffeurId,
      pageNo: 1,
      pageSize: 1,
      tripStatus: 1
    })
    if (res.data && res.code === 0) {
      this.setState({
        nowData: res.data,
        nowVisible: true
      })
    }
    this.setState({ nowLoading: false })
  }
  handleCancel = () => {
    this.setState({
      nowVisible: false
    })
  }

  render() {
    const { columns, dataSource, loading, pageData: { pageNo, pageSize }, total, title, visible, editValue, nowVisible, nowColumns, nowData, nowLoading, btnLoading } = this.state
    return (
      <div className='p-layout-box'>
        <SearchHeader getValue={this.getValue} openDialog={this.openDialog} />
        <div className="p-layout-content-pagination">
          <TheTable columns={columns} dataSource={dataSource} loading={loading} scroll={{ x: 'max-content', y: '63vh' }} />
          <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
        </div>
        <TheDialog
          width={400}
          title={title}
          visible={visible}
          footer={null}
          handleCancel={this.closeDialog}
        >
          <Form onFinish={this.saveDriver} initialValues={editValue}>
            <Form.Item label="司机姓名" name={'chauffeurName'} rules={[{ required: true }]}>
              <Input placeholder='请输入司机姓名' />
            </Form.Item>
            <Form.Item label="联系方式" name={'chauffeurMobile'} rules={[{ required: true }]}>
              <Input placeholder='请输入联系方式' />
            </Form.Item>
            <Form.Item>
              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                <Space>
                  <Button onClick={this.closeDialog}>取消</Button>
                  <Button loading={btnLoading} type='primary' htmlType='submit'>保存</Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog>
        <TheDialog
          title={'当前行程'}
          visible={nowVisible}
          handleCancel={this.handleCancel}
          handleOk={this.handleCancel}
          width="80vw"
        >
          <TheTable columns={nowColumns} dataSource={nowData} loading={nowLoading} />
        </TheDialog>
      </div>
    )
  }
}
